package com.lsy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lsy.dao.AccountMapper;
import com.lsy.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目名：springboot01
 * 包名：com.lsy.service
 * 类名：CustomUserDetailsService
 * 描述：
 * 作者：柳胜酉
 * 开始时间：2023/6/12
 * 完成时间：
 * 版本：1.0
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private AccountMapper accountMapper;
    @Override
    public UserDetails loadUserByUsername(String username)  {
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        //使用mybatis-plus从数据库读取用户信息
        LambdaQueryWrapper<Account> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Account::getAccount,username);
        Account account= accountMapper.selectOne(wrapper);
        //将用户信息封装成User返回
        if(account==null){
            throw new UsernameNotFoundException("用户名不存在");
        }else{
            List<GrantedAuthority> list=new ArrayList<>();
            list.add(new SimpleGrantedAuthority("ROLE_"+account.getRole()));
            User user=new User(account.getAccount(),account.getPassword(),list);
            return user;
        }
    }
}


